﻿using System.Windows;
using System.Windows.Data;
using System.Windows.Interactivity;
using NthDownload.Common.Validation;

namespace NthDownload.Common.Interactivity.Behaviors
{
    public class BindingGroupValidatorBinder : Behavior<BindingGroup>
    {
        #region Dependancy Properties

        #region BindingGroupValidator

        public BindingGroupValidator BindingGroupValidator
        {
            get { return (BindingGroupValidator)GetValue(BindingGroupValidatorProperty); }
            set { SetValue(BindingGroupValidatorProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Test.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty BindingGroupValidatorProperty =
            DependencyProperty.Register("BindingGroupValidator", typeof(BindingGroupValidator), typeof(BindingGroupValidatorBinder), new PropertyMetadata(null, new PropertyChangedCallback(BindingGroupValidatorChanged)));

        private static void BindingGroupValidatorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            BindingGroupValidatorBinder bindingGroupBridgeBinder = d as BindingGroupValidatorBinder;
            if (bindingGroupBridgeBinder == null) return;

            //
            // Unassociate with old binding group validator
            //
            BindingGroupValidator oldValue = e.OldValue as BindingGroupValidator;

            if (oldValue != null)
            {
                oldValue.BindingGroup = null;
            }

            //
            // Associate with new binding group bridge
            //
            BindingGroupValidator newValue = e.NewValue as BindingGroupValidator;

            if (newValue != null)
            {
                newValue.BindingGroup = bindingGroupBridgeBinder.AssociatedObject;
            }
        }

        #endregion BindingGroupValidator

        #endregion Dependancy Properties
    }
}
